//
//  PictureSelectorCollectionViewController.swift
//  SNS
//
//  Created by ios on 15/12/25.
//  Copyright © 2015年 WU. All rights reserved.
//

import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let rowCount: CGFloat = 5
private let margin: CGFloat = 5
private let maxImageCount = 9


class PictureSelectorViewController: UICollectionViewController {
    
    var imageList = [UIImage]()
    
    init() {
        //设置layout
        //1.计算每个cell的宽度
        let itemW = (screenW - (rowCount + 1) * margin) / rowCount
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.minimumInteritemSpacing = margin
        layout.minimumLineSpacing = margin
        //设置组间距
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        super.init(collectionViewLayout: layout)
        //修改集合视图的背景颜色
        collectionView?.backgroundColor = UIColor.whiteColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        // Register cell classes
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
        // Do any additional setup after loading the view.
    }
    
    // MARK: UICollectionViewDataSource
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let delta = imageList.count == maxImageCount ? 0 : 1
        return imageList.count + delta
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        //设置代理
        cell.delegate = self
        //设置数据源
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
    
}

extension PictureSelectorViewController: PictureSelectorCellDelegate{
    func userWillDeletePicture(cell: PictureSelectorCell) {
        print(cell)
        //1.通过获取的cell 找到对应的indexPath
        if let index = collectionView?.indexPathForCell(cell) {
            //在数组中 删除对应的indexPaht.item角标下的元素
            imageList.removeAtIndex(index.item)
            //操作完数据源 执行刷新
            collectionView?.reloadData()
        }
        
    }
    
    func userWillChosePicture(cell: PictureSelectorCell) {
        
        //如果点击的cell 的image不为nil 的话就直接返回
        if cell.image != nil {
            print("已经显示图片啦,不要再点啦")
            return
        }
        print(__FUNCTION__)
        //选择图片
        //1.得到图片选择器 控件
        let picker = UIImagePickerController()
        //modal出对应的图片选择器
        presentViewController(picker, animated: true, completion: nil)
        //询问用户访问权限 是iOS7之后  需要经过用户同意之后才能够获取用户个人隐私数据
        // 2.设置图片选择器的代理
        //一旦指定了代理对象 之后 就需要程序员手动dismiss picker
        picker.delegate = self
        //设置允许编辑 上传用户头像的时候 需要打开
        //        picker.allowsEditing = true
    }
}

extension PictureSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    /**
     图片选择器的协议方法
     
     - parameter picker:      图片选择器本身
     - parameter image:       表示用户选择的图片
     - parameter editingInfo: 编辑信息
     */
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        print(image)
        print(editingInfo)
        //将获取的图片 添加到数组中  修改数组
        imageList.append(image)
        //刷新列表
        collectionView?.reloadData()
        //手动dismiss
        dismissViewControllerAnimated(true, completion: nil)
    }
}

//-------------------------------------------------------


//1.定义协议
@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {
    //定义协议方法
    //添加图片
    optional func userWillChosePicture(cell: PictureSelectorCell)
    //删除图片 添加参数 把自己回调回去
    optional func userWillDeletePicture(cell: PictureSelectorCell)
}

class PictureSelectorCell: UICollectionViewCell {
    
    
    // MARK:定义外部模型属性
    var image: UIImage? {
        didSet {
            ///如果设置的图片为空的话  就隐藏删除按钮
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    @objc private func addBtnDidClick() {
        //使用代理调用协议方法
        //delegate? 表示 协议是否为空
        // userWillChosePicture! 必须实现协议方法
        delegate?.userWillChosePicture?(self)
    }
    
    @objc private func deleteBtnDidClick() {
        delegate?.userWillDeletePicture?(self)
    }
    
    
    //声明一个 弱引用的代理对象
    weak var delegate: PictureSelectorCellDelegate?
    // MARK:重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:设置页面 和 布局
    private func setupUI() {
        
        //设置图片的显示样式
        //ScaleAspectFit 导致图片显示的时候会留白
        addBtn.imageView?.contentMode = .ScaleAspectFill
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(addBtn.snp_top)
            make.right.equalTo(addBtn.snp_right)
        }
        //绑定按钮的事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
    }
    
    // MARK:懒加载所有的子视图
    private lazy var deleteBtn: UIButton = UIButton(imageName:nil , backImageName: "compose_photo_close")
    private lazy var addBtn: UIButton = UIButton(imageName: nil, backImageName: "compose_pic_add")
}
